import IShape from "../interfaces/IShape";
import Vector2 from "../maths/Vector2";
import ITransformable from "../interfaces/ITransformable";
import Math2D from "../maths/Math2D";
import IRenderState from "../interfaces/IRenderState";
import ERenderType from "../enums/ERenderType";
import Matrix2D from "../maths/Matrix2D";

export default class Line implements IShape {
    public start: Vector2;
    public end: Vector2;
    public data: any;

    public get type(): string {
        return "Line";
    }

    public constructor(len: number = 10, t: number = 0) {
        if (t < 0.0 || t > 1.0) {
            alert("参数t必须处于 [ 0 , 1 ]之间!!");
            throw new Error("参数t必须处于 [ 0 , 1 ]之间!!");
        }
        this.start = Vector2.create(- len * t, 0);
        this.end = Vector2.create(len * (1.0 - t), 0);
        this.data = undefined;
    }

    public hitTest(localPt: Vector2, transform: ITransformable): boolean {
        return Math2D.isPointOnLineSegment(localPt, this.start, this.end);
    }

    public beginDraw(transformable: ITransformable, state: IRenderState, context: CanvasRenderingContext2D): void {
        context.save();
        context.lineWidth = state.lineWidth;
        context.strokeStyle = state.strokeStyle;
        let mat: Matrix2D = transformable.getWorldMatrix();
        context.setTransform(mat.values[0], mat.values[1], mat.values[2], mat.values[3], mat.values[4], mat.values[5]);
    }

    public draw(transformable: ITransformable, state: IRenderState, context: CanvasRenderingContext2D): void {
        state.renderType = ERenderType.STROKE;
        context.beginPath();
        context.moveTo(this.start.x, this.start.y);
        context.lineTo(this.end.x, this.end.y);
        context.stroke();
    }

    public endDraw(transformable: ITransformable, state: IRenderState, context: CanvasRenderingContext2D): void {
        context.restore();
    }
}